/*
  规则设置
 */
define([ '../../common/service'], function (http) {
    var Widget = function () {
    }
    Widget.prototype = $.extend(Widget.prototype, {
        init: function () {
            var _this = this;

            //初始化tab
            $("div.ndp-tab-wrapper[name=plain-tab]").tabs({
                list:[I18N.getText("rulescriptList","roleListTitle"),
                    I18N.getText("rulescriptResult","ruleResult"),
                    I18N.getText("optRecords","optRecords"),
                    I18N.getText("rulescriptSetting","setting")]
            }).on("TAB_CHANGE",function(e){//点击其中的一个tab发生事件
                var href = "";
                switch (e.originalEvent.data.index){
                    case 0:
                        href = "#!rulescriptList";
                        break;
                    case 1:
                        href = "#!rulescriptResult";
                        break;
                    case 2:
                        href = "#!optRecords";
                        break;
                    case 3:
                        href = "#!rulescriptSetting";
                        break;
                }
                window.location.hash = href;
            }).val(3);//设置选中的tab 索引，默认0;

            //列表管理
            var settings = {supportDrag: false,supportAdjust:false,supportConfig:false};
            $('table[list-manager="ruleScriptList"]').listManager('init',settings, function(){
                _this.getList();
            });
        },
        /**
         * [_bindEnents 绑定事件]
         * @return {[type]} [description]
         */
        _bindEnents: function () {
            //绑定 输入框
            $(".modifyClass").click(function () {
                $(this).parent("div").addClass('hide');
                $(this).parent("div").next().removeClass('hide');
            });
            $("input[name='modify-value']").focusout(function () {
                var str = $(this).val();
                $(this).parent().addClass('hide');
                $(this).parent().prev().removeClass('hide');
                $(this).parent().prev().find("span").html(str);
            });
            $("input[name='modify-money']").focusout(function () {
                var str = $(this).val();
                $(this).parent().addClass('hide');
                $(this).parent().prev().removeClass('hide');
                $(this).parent().prev().find("span").html('$'+str);
            });
            $("input[name='modify-money']").blur(function(){
                checkNum($(this).get(0));
            });
            $("input[name='modify-money']").keyup(function(){
                clearNoNum($(this).get(0));
            });
            //绑定 弹出框事件
            $("#conditions-grid").find(".alertClass").click(function () {
                $("#accountModal").modal();
                var ids = $(this).closest("tr").data("ids");
                initAccountModal(ids);
                bindSaveEvent($(this).closest("tr"));
            });

            //绑定 save 按钮
            saveRuleSetting();
        },
        /*
         @获取列表数据
         */
        getList: function () {
            var _this = this;
            var loadingArea = $('#rule-setting-content');
            Kit.loading.show(loadingArea);
            http.do('/ruleSettings/list', {param: ''}, 'POST').then(function (res) {
            //_this.api.API('ruleSettings', 'list').load({
            //    success: function (msg, data) {
                    //操作DOM节点更换数据
                    var _tbody = $('#conditions-grid'),
                        tmpHtml = '',
                        _list = res.data;

                    for (var i = 0; i < _list.length; i++) {
                        tmpHtml += '<tr connObjId="'+ _list[i].connObjId +'">';

                        //id
                        if (_list[i].select) {
                            tmpHtml += '<td><label class=""><input type="checkbox" name="checkbox-inline" checked="checked"><i></i></label></td>';
                        } else {
                            tmpHtml += '<td><label class=""><input type="checkbox" name="checkbox-inline"><i></i></label></td>';
                        }
                        tmpHtml += '<td title="' + _list[i].connObjName + '" class="text-left">' + _list[i].connObjName + '</td>';
                        tmpHtml += '<td title="' + _list[i].platform + '" class="text-left">' + _list[i].platform + '</td>';
                        //选择账号
                        var names = [];
                        for (var j = 0; j < _list[i].fbAccounts.length; j++) {
                            if (_list[i].fbAccounts[j].select) {
                                names.push(_list[i].fbAccounts[j].fbAccountname);
                            }
                        }
                        tmpHtml += '<td title="' + names.join() + '" class="text-left">'
                            + '<div><a href="javascript:void(0)" class="td-a-budget alertClass icon-btn"><i class="fa fa-edit"></i></a><span class="namesDiv">' + names.join() + '</span></div>'
                            + '</td>';
                        //adSetName
                        tmpHtml += '<td title="' + _list[i].keyWord + '" class="text-left">'
                            + '<div><a href="javascript:void(0)" class="td-a-budget modifyClass icon-btn"><i class="fa fa-edit"></i></a><span class="keywordDiv">' + _list[i].keyWord + '</span></div>'
                            + '<label class="input hide"><input class="input-budget" type="text" size="8" value="' + _list[i].keyWord + '"  name="modify-value"></label>'
                            + '</td>';
                        //版本
                        tmpHtml += '<td title="$' + accDiv(_list[i].lossLimits, 100) + '" class="text-left">'
                            + '<div><a href="javascript:void(0)" class="td-a-budget modifyClass icon-btn"><i class="fa fa-edit"></i></a><span class="limitDiv">$' + accDiv(_list[i].lossLimits, 100) + '</span></div>'
                            + '<label class="input hide"><input class="input-budget" type="text" size="6" value="' + accDiv(_list[i].lossLimits, 100) + '"  name="modify-money"></label>'
                            + '</td>';
                        tmpHtml += '</tr>';
                    }
                    _tbody.html(tmpHtml);
                    //临时数据缓存
                    $("#conditions-grid").find("tr").each(function (i) {
                        $(this).data("ids", _list[i].fbAccounts);
                    });
                    $('table[list-manager="ruleScriptList"]').listManager('resetTd', false);
                    _this._bindEnents();
                    Kit.loading.hide(loadingArea);
                },function (msg) {
                    Kit.alert(msg || I18N.getText("rulescriptSetting","failedMsg"));
                    Kit.loading.hide(loadingArea);
                });
        }
    });
    function initAccountModal(ids) {
        $("#accountBody").html("");
        var html = " <form class='smart-form'><ul class='inline-group'>";
        for (var i = 0; i < ids.length; i++) {
            if (ids[i].select) {
                html += '<li><label class=""><input type="checkbox" name="checkbox-inline" checked="checked" value="' + ids[i].fbAccountId + '"><i></i></label> <span name="' + ids[i].fbAccountname + '">'
                    + ids[i].fbAccountname + '(' + ids[i].fbAccountId + ')</span></li>';
            } else {
                html += '<li><label class=""><input type="checkbox" name="checkbox-inline" value="' + ids[i].fbAccountId + '"><i></i></label> <span name="' + ids[i].fbAccountname + '">' + ids[i].fbAccountname + '(' + ids[i].fbAccountId + ')</span></li>';
            }
        }
        html += '</ul></form>';
        $("#accountBody").html(html);
    }

    /**
     * 除法函数
     * @param arg1
     * @param arg2
     * @returns {number}
     */
    function accDiv(arg1, arg2) {
        var t1 = 0, t2 = 0, r1, r2, n;
        try {
            t1 = arg1.toString().split(".")[1].length;
        }
        catch (e) {
            t1 = 0;
        }
        try {
            t2 = arg2.toString().split(".")[1].length;
        }
        catch (e) {
            t2 = 0;
        }
        r1 = Number(arg1.toString().replace(".", ""));
        r2 = Number(arg2.toString().replace(".", ""));
        //n = Math.max(t1,t2);
        return (r1 / r2) * Math.pow(10, t2 - t1);
    }

    /**
     * 乘法
     * @param arg1
     * @param arg2
     * @returns {number}
     */
    function accMul(arg1,arg2)
    {
        var t1 = 0, t2 = 0, r1, r2;
        try
        {
            t1 = arg1.toString().split(".")[1].length;
        }
        catch(e)
        {t1 = 0;}
        try
        {
            t2 = arg2.toString().split(".")[1].length;
        }
        catch(e)
        {t2 = 0;}
        r1 = Number(arg1.toString().replace(".",""));
        r2 = Number(arg2.toString().replace(".",""));
        return (r1*r2)/Math.pow(10, t2+t1);
    }


    /**
     * 绑定save btn
     * @param $Dom
     */
    function bindSaveEvent($Dom) {
        $("#accountModal").find(".btn-primary").unbind("click").bind("click", function () {
            //收集数据重新set cache
            var fbAccounts = [];
            var names = [];
            $("#accountBody").find("input:checked").each(function () {
                var act = {};
                act.fbAccountId = $(this).val();
                act.fbAccountname = $(this).parent().next("span").attr("name");
                act.select = true;
                fbAccounts.push(act);
                names.push(act.fbAccountname);
            });
            $("#accountBody").find("input:not(:checked)").each(function () {
                var act = {};
                act.fbAccountId = $(this).val();
                act.fbAccountname = $(this).parent().next("span").attr("name");
                act.select = false;
                fbAccounts.push(act);
            });
            $Dom.data("ids", fbAccounts);
            $Dom.find("td").eq(3).find("span").html(names.join());
        });
    }

    function saveRuleSetting() {
        $("#saveRultSettingDom").click(function () {
            var data = [];
            //被选中的行
            $("#conditions-grid").find("tr").each(function (index, element) {
                if ($(this).find("td>label>input:checked").length != 0 && $(this).find("td>label>input:checked")) {
                    var obj = {};
                    $(this).find("td").each(function (i) {
                        var text = $(this).text();
                        switch (i) {
                            case 0:
                            case 3:
                                break;
                            case 1:
                                obj.connObjName = text;
                                break;
                            case 2:
                                obj.platform = text;
                                break;
                            case 4:
                                obj.keyWord = text;
                                break;
                            case 5:
                                obj.lossLimits = accMul(text.replace("$", "") , 100);
                                break;
                        }
                    });
                    obj.connObjId = element.getAttribute('connObjId');
                    obj.select = true;
                    //过滤
                    obj.fbAccounts = [];
                    var list = $(this).data("ids");
                    for (var i = 0; i < list.length; i++) {
                        if (list[i].select) {
                            obj.fbAccounts.push(list[i]);
                        }
                    }
                    data.push(obj);
                }
            });
            //处理 setting后的数据
            saveData(data);
        });
    }

    /**
     * 处理修改过的、checked tr的data
     * @param data
     */
    function saveData(_data) {
        http.do('/ruleSettings/save', {param: JSON.stringify(_data)}, 'POST').then(function (res) {
        //myApi.API('ruleSettings', 'save', _data).load({
        //    success: function (msg, data) {
                if(res.flag = "success"){
                    Kit.alert_success('保存优化设置成功！');
                }else{
                    Kit.alert2('保存优化设置失败！');
                }
            },function (msg) {
                Kit.alert2(msg || '保存失败！');
            }
        );
    }
    function clearNoNum(obj){
        obj.value = obj.value.replace(/[^\d.]/g,"");
        obj.value = obj.value.replace(/^\./g,"");
        obj.value = obj.value.replace(/\.{2,}/g,".");
        obj.value = obj.value.replace(".","$#$").replace(/\./g,"").replace("$#$",".");
    }
    function checkNum(obj){
        obj.value = obj.value.replace(/\.$/g,"");
    }

    return new Widget();
})
